<?php

namespace front\modules\web\controllers;

use goods\services\ProductService;
use Yii;
use yii\data\ActiveDataProvider;
use front\controllers\WebBaseController;
use yii\helpers\Json;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;
use goods\services\CollectionService;

/**
 * CollectionController implements the CRUD actions for CollectionModel model.
 */
class CollectionController extends WebBaseController
{
    public $layout = 'main';

    public $enableCsrfValidation = false;

    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }


    /**
     *  取消单个商品收藏
     * @return \yii\web\Response
     */
    public function actionRemove()
    {
        $id = yii::$app->request->get('id');
        if(!$id){
            WebBaseController::getAjaxData(2,'该收藏不存在');
        }
        $info = CollectionService::remove($id);
        if($info['code']==1){
            WebBaseController::getAjaxData(3,'删除失败');
        }
        $status = 1;
        echo trim($_GET['funcName']).'('.json_encode(array('status'=>$status)).')';
    }

    /**
     *  清空回收站
     * @return \yii\web\Response
     */
    public function actionClean()
    {
        CollectionService::clean();
        return $this->redirect('index');
    }

    /**
     * 添加商品收藏
        $params=[
            'C_Id'=>20,
            'P_Id'=>20,
            'p_name'=>'ewqe',
            'pic'=>'http://www.baidu.com',
            'attributes'=>[
                'color' => '红色',
                'size' => '大',
                'price' => '255'
            ],
        ];
     */
    public function actionAdd(){
        $params = yii::$app->request->get();
        $info = CollectionService::addCollection($params);
        if($info['code']==1){
            WebBaseController::getAjaxData(2,'参数错误');
        }
        return $this->redirect(Yii::$app->user->getReturnUrl());
    }

    /**
     * Lists all CollectionModel models.
     * @return mixed
     */
    public function actionIndex()
    {
        $data['getByWeb'] = 1;
        $info = CollectionService::getCollection($data);
        $info = ArrayHelper::toArray($info['result']);
        if(!empty($info)) {
            foreach ($info as $key => $item) {
                $price = ProductService::getPrice($item['P_Id']);
                $info[$key]['price'] = static::price_format($price);
            }
        }else{
            $info = [];
        }
        return $this->render('index',['data'=>$info]);
    }
}
